package com.tx.studentManager.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.tx.studentManager.exception.BaseException;
import com.tx.studentManager.model.ErrorInfo;
import com.tx.studentManager.model.User;
import com.tx.studentManager.service.UserService;
import com.tx.studentManager.utils.Constants;

@Controller
public class LoginController {
	@Autowired
	private UserService userService;

	@RequestMapping("login")
	public String login(HttpServletRequest request, HttpServletResponse response) {
		return "/auth/login";
	}

	@RequestMapping("to_login")
	public String to_login(Model model, String username,
			@RequestParam(value = "password") String pwd,
			@RequestParam(required = true) String validCode,
			HttpServletRequest request) {

		// HttpSession session = request.getSession(true);
		String errorMessage = "";
		try {
			if (!checkValidCode(request, validCode)) {
				errorMessage = "验证码错误";
			} else {
				Subject subject = SecurityUtils.getSubject();

				UsernamePasswordToken token = new UsernamePasswordToken(
						username, pwd);
				// token.setRememberMe(true);
				try {
					subject.login(token);
					User loginedUser = userService.getUserByUserName(username);
					subject.getSession().setAttribute(
							Constants.USER_SESSION_NAME, loginedUser);
					// 重定向到首页
					return "redirect:/admin/index";
				} catch (UnknownAccountException uae) {
					errorMessage = "用户不存在";
				} catch (IncorrectCredentialsException ice) {
					errorMessage = "密码错误";
				} catch (LockedAccountException lae) {
					errorMessage = "账户被锁定";
				} catch (AuthenticationException e) {
					errorMessage = "登录失败错误信息：" + e;
					e.printStackTrace();
					token.clear();
				}
			}
		} catch (InvalidSessionException e) {
			e.printStackTrace();
		} catch (BaseException e) {
			ErrorInfo errorInfo = new ErrorInfo();
			errorInfo.setErrorMsg("验证码失效，请返回并刷新页面再登录！");
			errorInfo.setDirectUrl("login");
			errorInfo.setUrlName("重新登陆");
			model.addAttribute("errorInfo", errorInfo);
//			e.printStackTrace();
			return "common/error";
		}
		model.addAttribute("ErrorMessage", errorMessage);
		return "/auth/login";
	}

	/**
	 * 
	 * @描述 退出登录
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("logout")
	public String logout(HttpServletRequest request,
			HttpServletResponse response) {
		Subject currentSubject = SecurityUtils.getSubject();
		currentSubject.logout();
		currentSubject.getSession()
				.removeAttribute(Constants.USER_SESSION_NAME);
		System.out.println("contetpath:" + request.getContextPath());
		return "redirect:login";
	}

	/**
	 * 验证输入验证码是否正确
	 * 
	 * @param request
	 * @param validCode
	 * @return
	 * @throws BaseException
	 */
	private boolean checkValidCode(HttpServletRequest request, String validCode)
			throws BaseException {
		String sessionCode = (String) request.getSession().getAttribute(
				Constants.KAPTCHA_SESSION_KEY);
		if (sessionCode == null) {
			throw new BaseException("1001", "验证码失效！");
		}
		if (sessionCode.equals(validCode)) {
			return true;
		}
		return false;
	}

	@RequestMapping("/registe")
	public String regedit() {
		return "auth/userRegiste";
	}

	@RequestMapping(value = "userRegiste", method = RequestMethod.POST)
	public String regeditUser(HttpServletRequest request, ModelMap map,
			User user) {

		User returnUser = userService.registeUser(user);
		if (returnUser == null) {
			Map<String, String> errorInfo = new HashMap<String, String>();
			errorInfo.put("error_code", "555");
			errorInfo.put("error_mess", "注册失败，请稍后再试！");
			errorInfo.put("error_backUrl", "/regedit");
			map.put("errorInfo", errorInfo);
			return "errorAndEception/error";
		}
		return "redirect:" + request.getContextPath();
	}

}
